const amqpLib = require('amqplib');
const amqpConfig = require('../../../config/amqp');
let amqpConnection = null;

async function getAmqpConnection () {
    if (amqpConnection == null) {
        let endpoint = amqpConfig.developmentEndpoint;
        let vhost = amqpConfig.developmentVhost;
        if (process.env.NODE_ENV === 'release') {
            endpoint = amqpConfig.productionEndpoint;
            vhost = amqpConfig.productionVhost;
        }
        if (process.env.NODE_ENV === 'trial') {
            endpoint = amqpConfig.stagingEndpoint;
            vhost = amqpConfig.stagingVhost;
        }
        amqpConnection = await amqpLib.connect({
            protocol: 'amqp',
            hostname: endpoint,
            port: amqpConfig.port,
            username: amqpConfig.username,
            password: amqpConfig.password,
            vhost
        });
        console.log('Amqp Conected');
    }
    return amqpConnection;
}

module.exports = {
    getAmqpConnection
};
